package cn.wolfcode.trip.base.controller;

import cn.wolfcode.trip.base.domain.*;
import cn.wolfcode.trip.base.query.FriendsQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.*;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 相当于@Controller + @ResponseBody
@RestController
// 提取出来"/users"
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IFriendsService friendsService;
    @Autowired
    private IMyInfoService infoService;
    @Autowired
    private ISystemMsgService systemMsgService;
    @Autowired
    private IUserGoodService userGoodService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IUserCollectService userCollectService;
    @Autowired
    private IMyInfoTempService infoTempService;



    /**
     * 注册用户
     * @param u
     * @return
     */
    // 表示请求方式是post
    @PostMapping
    public Object regist(User u){
        JSONResult result = new JSONResult();
        try {
            // 注册
            userService.regist(u);
            // 把注册的user对象封装到JSONResult的result中
            result.setData(u);
        } catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        // 返回封装的结果对象
        return result;
    }


    /**
     * 更新用户信息
     * @param u
     * @return
     */
    @PutMapping("/{id}")
    public Object saveOrUpdate(User u){
        JSONResult result = new JSONResult();

        try {
            // 调用业务层方法
            userService.saveOrUpdate(u);
            // 设置当前登陆的用户，一起返回
            result.setData(u);
        } catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        // 返回封装的结果对象
        return result;
    }

    /**
     * 获得用户的所有游记
     * @param qo
     * @return
     */
    @GetMapping("/{authorId}/travels")
    public Object queryTravel(TravelQueryObject qo){
        // 设置按照最近更新时间
        qo.setOrderBy("t.lastUpdateTime desc");
        return travelService.queryTravel(qo);
    }

    /**
     * 保存用户的游记
     * @param entity
     * @return
     */
    @PostMapping("/{authorId}/travels")
    public Object saveTravels(Travel entity){
        // 自动填充作者
        entity.setAuthor(UserContext.getCurrentUser());
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /**
     * 更新用户的游记
     * 资源：users/{authorId}/travels
     * 动作:put
     * 参数：很多
     */
    @PutMapping("/{authorId}/travels")
    public Object saveOrUpdate(Travel entity){
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /*
        查看我的消息列表
        资源: /users/{id}/infos
	    动作:GET
	    参数:
     */
    @GetMapping("/{id}/infos")
    public Object getUserInfo(@PathVariable Long id){
        return infoService.getInfoByUserId(id);
    }

    /*
        查看系统消息
        资源: /users/{id}/systemMsg
        动作:GET
        参数:
     */
    @GetMapping("/{id}/systemMsg")
    public Object getUserSystemMsg(@PathVariable Long id, QueryObject qo){
        qo.setOrderBy("time desc");
        return systemMsgService.selectUserSystemMsg(qo, id);
    }


    /*
        查看点赞信息
        资源: /users/{id}/addGoodMsgs
        动作:GET
        参数:
     */
    @GetMapping("/{id}/addGoodMsgs")
    public Object queryAddGoodMsg(@PathVariable Long id, QueryObject qo){
        qo.setPageSize(10);
        qo.setOrderBy("ug.time desc");
        return userGoodService.userAddGoodMsg(id, qo);
    }

    /*
        查看评论信息
        资源: /users/{id}/commentMsgs
        动作:GET
        参数:
     */
    @GetMapping("/{id}/commentMsgs")
    public Object queryCommentMsg(@PathVariable Long id, QueryObject qo){
        qo.setPageSize(10);
        qo.setOrderBy("time desc");
        return commentService.userCommentMsg(id, qo);
    }

    /*
        清空用户临时点赞信息
        资源: /users/{id}/commentMsgs
        动作:GET
        参数:
     */
    @DeleteMapping("/{id}/{msgType}")
    public Object clearTempMsg(@PathVariable Long id, @PathVariable String msgType) {
        infoTempService.emptyTempMsg(id, msgType);
        return new JSONResult();
    }



    /**
     * 查询用户的关注和粉丝数量
     * 资源：users/{id}
     * 动作:get
     * 参数：id
     */
    @GetMapping("/{id}/fansOrFollow")
    public Object selectInterface(@PathVariable Long id){
        return userService.selectInterface(id);
    }

    /**
     * 查询用户有哪些粉丝
     * 资源：/friends/{fansId}
     * 动作:get
     * 参数：fansId
     */
    @GetMapping("/{toUserId}/fans")
    public Object selectFans(FriendsQueryObject qo){
        qo.setOrderBy("f.followTime desc");
        return friendsService.selectFans(qo);
    }

    /**
     * 查询用户关注了哪些人
     * 资源：/friends/{fansId}
     * 动作:get
     * 参数：fansId
     */
    @GetMapping("/{userId}/follow")
    public Object selectFollow(FriendsQueryObject qo){
        qo.setOrderBy("f.followTime desc");
        return friendsService.selectFollow(qo);
    }

    // 根据用户 id 查询用户信息
    @GetMapping("/{id}")
    public Object getUser(@PathVariable Long id){
        return userService.getUser(id);
    }

    // 关注功能
    @PutMapping("/{userId}/follow/{toUserId}")
    public Object fansOrFollow(@PathVariable Long userId, @PathVariable Long toUserId){
        userService.fansOrFollow(userId, toUserId);
        return new JSONResult();
    }

    // 查询是否已经关注, 从而判断进行关注或是取消关注
    @GetMapping("/{userId}/follow/{toUserId}")
    public Object getfansOrFollow(@PathVariable Long userId, @PathVariable Long toUserId) {
        JSONResult result = new JSONResult();
        try {
            Friends friends = friendsService.getfansOrFollow(userId, toUserId);
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    // 取消关注
    @DeleteMapping("/{userId}/follow/{toUserId}")
    public Object deleteFansOrFollow(@PathVariable Long userId, @PathVariable Long toUserId) {
        friendsService.deleteFansOrFollow(userId, toUserId);
        return new JSONResult();
    }

    // 根据用户 id 查询已公开的游记
    @GetMapping("/{authorId}/travelCount")
    public Object getTravelCountById(@PathVariable Long authorId) {
        return travelService.getTravelCountById(authorId);
    }



    /**
     * 检查用户是否以及点赞
     * 资源：users/{userId}/{goodId}
     * 动作:GET
     * 参数：
     */
    @GetMapping("/{userId}/addGoods/{goodId}")
    public Object checkAddGood(@PathVariable Long userId, @PathVariable Long goodId) {
        JSONResult result = new JSONResult();
        try {
            userGoodService.checkAddGood(userId, goodId);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }


     /*
        根据查看类型查找该类型的评论
        资源:users/{userId}/comments
        动作:GET
        参数:type=评论类型
     */
     @GetMapping("/{userId}/comments")
     public Object getUserCommentByType(@PathVariable Long userId, String type) {
         JSONResult result = new JSONResult();
         try {
             List <Comment> list = commentService.getUserCommentByType(userId, type);
             result.setData(list);
         } catch (Exception e) {
             e.printStackTrace();
             result.mark(e.getMessage());
         }
         return result;
     }

     /*
        根据类型查询该用户某个评论的总数
          资源:users/{userId}/commentsCount
          动作:GET
          参数:type=评论类型
      */
     @GetMapping("/{userId}/commentsCount")
     public Object getUserCommentsCountByType(@PathVariable Long userId, String type) {
         JSONResult result = new JSONResult();
         try {
            int count = commentService.getUserCommentsCountByType(userId, type);
             result.setData(count);
         } catch (Exception e) {
             e.printStackTrace();
             result.mark(e.getMessage());
         }
         return result;
     }

    /**
     * 检查用户是否以及收藏
     * 资源：users/{userId}/{collectId}
     * 动作:GET
     * 参数：
     */
    @GetMapping("/{userId}/addCollects/{collectId}")
    public Object checkAddCollect(@PathVariable Long userId, @PathVariable Long collectId) {
        JSONResult result = new JSONResult();
        try {
            userCollectService.checkAddCollect(userId, collectId);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 购买商品后，更新用户积分
     * 资源：users/{id}/prices
     * 动作:put
     * 参数：很多
     */
    @PutMapping("/{id}/{integral}")
    public Object updateIntegral(@PathVariable Long id, @PathVariable Long integral){
        Long balance = integral;
        userService.updateIntegralByPrice(id, balance);
        return new JSONResult();
    }


     /*
        根据类型查询该用户对该类型的收藏
           资源:users/{userId}/collect
           动作:GET
           参数:type=类型
      */
     @GetMapping("/{userId}/collect")
     public Object getUserCollectByType(@PathVariable Long userId, String type) {
         JSONResult result = new JSONResult();
         try {
             List<UserCollect> list = userCollectService.getCollectsByType(userId,type);
             result.setData(list);
         } catch (Exception e) {
             e.printStackTrace();
         }
         return result;
     }

    /*
       根据类型查询该用户某个评论的总数
         资源:users/{userId}/commentsCount
         动作:GET
         参数:type=评论类型
     */
    @GetMapping("/{userId}/collectsCount")
    public Object getCollectsCountByType(@PathVariable Long userId, String type) {
        JSONResult result = new JSONResult();
        try {
            int count = userCollectService.getCollectsCountByType(userId, type);
            result.setData(count);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

     /*
        查询出所有用户的信息
        资源:/users
        动作:GET
        参数:
      */
     @GetMapping
    public Object getAllUsers(){
         return userService.selectAllUsers();
     }
}
